package socket;
/*基于Client类生成一个图形化界面，要求上方包含一个文本域用于接收服务端返回的信息，
下方包含一个输入框用于发送信息，按回车发送消息，并包含输入提示框*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ClientGUI extends JFrame {
    private Socket socket;
    private JTextArea textArea;
    private JTextField textField;
    private PrintWriter writer;
    private BufferedReader reader;

    public ClientGUI() {
        super("Chat Client");

        try {
            System.out.println("正在连接服务器...");
            socket = new Socket("localhost", 8080);
            System.out.println("连接成功");

            // 设置流
            OutputStream out = socket.getOutputStream();
            writer = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8), true);

            InputStream in = socket.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

            // 输入昵称
            String nickname = JOptionPane.showInputDialog(this, "请输入昵称:");
            if (nickname != null && !nickname.trim().isEmpty()) {
                writer.println(nickname);
            } else {
                JOptionPane.showMessageDialog(this, "昵称不能为空！");
                return;
            }

            // 创建GUI组件
            textArea = new JTextArea(20, 50);
            textField = new JTextField(20);

            // 添加监听器到文本框
            textField.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String message = textField.getText();
                    textField.setText("");
                    writer.println(message);
                }
            });

            // 布局管理
            setLayout(new BorderLayout());
            add(new JScrollPane(textArea), BorderLayout.CENTER);
            add(textField, BorderLayout.SOUTH);

            // 启动接收消息线程
            Thread receiveThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String messageFromServer;
                        while ((messageFromServer = reader.readLine()) != null) {
                            textArea.append(messageFromServer + "\n");
                        }
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            });
            receiveThread.setDaemon(true);
            receiveThread.start();

            // 设置窗口大小
            setSize(600, 400);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLocationRelativeTo(null); // 居中显示
            setVisible(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ClientGUI();
    }
}
